<template>
  <div class="article">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
    <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
      <van-cell
      v-for="(item,index) in list"
      :key="index"
      :title="item.title"
      @click="$router.push('/article/'+item.art_id.toString())">
        <!-- 这块不是很理解 -->
       <div slot="label">
          <van-grid :column-num="item.cover.images.length">
            <van-grid-item v-for="(img,index) in item.cover.images" :key="index" >
              <van-image :src='img' lazy-load/>
            </van-grid-item>
          </van-grid>
          <!-- 文字说明 -->
          <div class="meta">
            <span>{{item.aut_name}}</span>
            <span>{{item.comm_count}}</span>
            <span>{{item.pubdate | dateFormat}}</span>
            <!-- 判断是否有token值 进行显示× -->
            <span v-if="$store.state.tokenInfo.token" @click="hClose(item)" class="cross"><van-icon name="cross" /></span>
          </div>
      </div>
      </van-cell>
    </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticle } from '@/api/article'
export default {
  name: 'ArticleList',
  props: ['channel'],
  created () {
    this.$eventBus.$on('delArticle', obj => {
      const { articleId, channelId } = obj
      if (channelId !== this.channel.id) {
        console.log('不是这个频道的内容');
        return
      }
      const idx = this.list.findIndex(article => article.art_id.toString() === articleId)
      if (idx !== -1) {
        this.list.splice(idx, 1)
      }
    })
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      isLoading: false
    }
  },
  methods: {
    hClose (article) {
      this.$emit('showMoreAction', article.art_id.toString())
    },
    async onLoad () {
      if (!this.timestamp) {
        this.timestamp = Date.now()
      }
      const result = await getArticle(this.channel.id, this.timestamp)
      this.timestamp = result.data.data.pre_timestamp
      // 第一步给list添加数据
      this.list.push(...result.data.data.results)
      // 第二步将loading的状态设置false
      this.loading = false
      // 第三步判断数据是否加载完成
      if (this.list.length >= 40) {
        this.finished = true
      }
    },
    async onRefresh () {
      const result = await getArticle(this.channel.id, Date.now())
      this.list.unshift(...result.data.data.results)
      this.$toast('刷新完成')
      this.isLoading = false
    }
  }
}
</script>

<style lang='less' scoped>
.meta {
  display: flex;
  span{
    margin-right:10px
  }
  .cross {
    margin-left: auto
  }
}
</style>
